package com.joshua.netdemo.JavaScriptDemo;

import android.os.Handler;
import android.webkit.WebView;

import com.joshua.netdemo.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @description:
 * @author: JoshuaWong E-mail:joshuawongchn@gmail.com
 * @date: 2017年01月04日 16:05
 * @version: 1.0
 */

public class MyObject {
    private Handler mHandler;
    private WebView mWebView;

    public MyObject(HTMLAty htmlAty, Handler handler) {
        this.mWebView = (WebView) htmlAty.findViewById(R.id.id_web_view);
        this.mHandler = handler;
    }

    public void init() {
        // 通过handler来确保init方法的执行在handler绑定在Activity的主线程中
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // 调用客户端setContactInfo方法
                mWebView.loadUrl("javascript:setContactInfo('" + getJsonStr() + "')");
            }
        });
    }

    public static String getJsonStr() {
        try {
            JSONObject object = new JSONObject();
            object.put("id", 1);
            object.put("name", "张三");
            object.put("phone", "123456");
            JSONObject object1 = new JSONObject();
            object1.put("id", 2);
            object1.put("name", "李四");
            object1.put("phone", "456789");
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(object);
            jsonArray.put(object1);
            return jsonArray.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
